package cn.iocoder.yudao.module.book.util;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.ObjectWriteResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
public class MinioUtils {

    private static final Logger log = LoggerFactory.getLogger(MinioUtils.class);

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket.name:image}")
    private String bucketName;

    public List<String> upload(MultipartFile[] multipartFiles) {
        List<String> names = new ArrayList<>(multipartFiles.length);
        for (MultipartFile file : multipartFiles) {
            String originalFilename = file.getOriginalFilename();
            String fileName = generateUniqueFileName(originalFilename);

            try (InputStream in = file.getInputStream()) {
                long fileSize = file.getSize();
                ObjectWriteResponse response = minioClient.putObject(PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .stream(in, fileSize, -1)
                        .contentType(file.getContentType())
                        .build());

                log.info("文件 {} 上传成功，ETag: {}", fileName, response.etag());
                names.add(fileName);
            } catch (Exception e) {
                log.error("MinIO 文件上传失败: {}", fileName, e);
                throw new RuntimeException("MinIO 文件上传失败", e);
            }
        }
        return names;
    }

    private String generateUniqueFileName(String originalFilename) {
        String[] split = originalFilename.split("\\.");
        if (split.length > 1) {
            return split[0] + "_" + System.currentTimeMillis() + "." + split[1];
        } else {
            return originalFilename + "_" + System.currentTimeMillis();
        }
    }
}